package com.jshan.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jshan.common.annotation.OperationLog;
import com.jshan.base.entity.SysMenu;
import com.jshan.service.SysMenuService;
import com.jshan.base.vo.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

import java.util.List;

@Tag(name = "菜单管理接口")
@RestController
@RequestMapping("/menu")
@RequiredArgsConstructor
public class SysMenuController {
    private final SysMenuService menuService;

    @Operation(summary = "查询用户菜单列表")
    @GetMapping("/list")
    public Result<List<SysMenu>> getMenuList() {
        Long userId = StpUtil.getLoginIdAsLong();
        List<SysMenu> menuTree = menuService.getMenuListByUserId(userId);
        return Result.ok(menuTree);
    }

    @SaCheckPermission("system:menu:list")
    @Operation(summary = "查询菜单分页列表")
    @GetMapping("/page")
    public Result<IPage<SysMenu>> getMenuPage(@RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam String menuName) {
        return Result.ok(menuService.getMenuPage(new Page<>(pageNum, pageSize), menuName));
    }

    @OperationLog("查询所有菜单列表")
    @GetMapping("/all")
    public Result<List<SysMenu>> getAllMenus() {
        List<SysMenu> allMenus = menuService.getAllMenus();
        return Result.ok(allMenus);
    }

    @SaCheckPermission("system:menu:add")
    @OperationLog("新增菜单")
    @PostMapping
    public Result<Void> addMenu(@RequestBody SysMenu menu) {
        menuService.save(menu);
        return Result.ok();
    }

    @SaCheckPermission("system:menu:edit")
    @OperationLog("修改菜单")
    @PutMapping
    public Result<Void> updateMenu(@RequestBody SysMenu menu) {
        menuService.updateById(menu);
        return Result.ok();
    }

    @SaCheckPermission("system:menu:delete")
    @OperationLog("删除菜单")
    @DeleteMapping("/{id}")
    public Result<Void> deleteMenu(@PathVariable Long id) {
        // 检查是否有子菜单
        if (menuService.hasChildren(id)) {
            return Result.fail(500, "存在子菜单，不允许删除");
        }
        menuService.removeById(id);
        return Result.ok();
    }
}
